import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/models/me.dart';
import 'package:fsharing/core/viewmodels/pages/mine/user_avatar_update_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/main.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:image_picker/image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

class UserPage extends StatefulWidget {
  final Me me;

  UserPage({
    Key key,
    @required this.me,
  }) : super(key: key);

  @override
  _UserPageState createState() => _UserPageState();
}

class _UserPageState extends State<UserPage> {
  String _nickname;
  String _mobile;

  @override
  Widget build(BuildContext context) {
    return BackgroundContainer(
      child: Scaffold(
        appBar: AppBar(
          leading: RoundBackButton(),
          title: Text('个人信息'),
        ),
        body: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Theme(
                data: lightTheme(),
                child: Material(
                  child: Column(
                    children: <Widget>[
                      _ItemAvatarWidget(
                        title: '头像',
                        value: widget.me.avatar,
                      ),
                      _DividerWidget(),
                      _ItemTextWidget(
                        title: '昵称',
                        value: _nickname ?? widget.me.nickname,
                        onTap: () {
                          _onNicknameClicked(context);
                        },
                      ),
                      _DividerWidget(),
                      _ItemTextWidget(
                        title: '电话',
                        value: _mobile ?? widget.me.mobile,
                        onTap: () {
                          _onMobileClicked(context);
                        },
                      ),
                      _DividerWidget(),
                      _ItemQRCodeWidget(
                        title: '二维码',
                      ),
                    ],
                  ),
                ),
              ),
              SizedBox(height: 10),
              Theme(
                data: lightTheme(),
                child: Material(
                  child: Column(
                    children: <Widget>[
                      _ItemTextWidget(
                        title: '真实姓名',
                        value: widget.me.realName,
                        showArrow: false,
                      ),
                      _DividerWidget(),
                      _ItemTextWidget(
                        title: '性别',
                        value: '未知',
                        showArrow: false,
                      ),
                      _DividerWidget(),
                      _ItemTextWidget(
                        title: '生日',
                        value: widget.me.birthday,
                        showArrow: false,
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _onNicknameClicked(BuildContext context) async {
    var result = await Navigator.of(context).pushNamed('/user/nickname', arguments: widget.me);
    if (result != null && result is String) {
      setState(() {
        _nickname = result;
      });
    }
  }

  void _onMobileClicked(BuildContext context) async {
    var result = await Navigator.of(context).pushNamed('/user/mobile', arguments: widget.me);
    if (result != null && result is String) {
      setState(() {
        _mobile = result;
      });
    }
  }
}

class _DividerWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Divider(height: 1, indent: 17, color: Colors.black12);
  }
}

class _ItemAvatarWidget extends StatelessWidget {
  final String title;
  final String value;

  const _ItemAvatarWidget({
    Key key,
    @required this.title,
    @required this.value,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => UserAvatarUpdateModel(Provider.of(context, listen: false)),
      child: Consumer<UserAvatarUpdateModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Container(
                height: 50,
                child: Row(
                  children: <Widget>[
                    SizedBox(width: 17),
                    Expanded(
                      child: Text(
                        title,
                        style: TextStyle(fontSize: 16),
                      ),
                    ),
                    CircularProgressIndicator(),
                    SizedBox(width: 16),
                  ],
                ),
              );
            default:
              return InkWell(
                child: Container(
                  height: 50,
                  child: Row(
                    children: <Widget>[
                      SizedBox(width: 17),
                      Expanded(
                        child: Text(
                          title,
                          style: TextStyle(fontSize: 16),
                        ),
                      ),
                      ClipRRect(
                        borderRadius: BorderRadius.circular(4),
                        child: model.file != null
                            ? Image.file(
                                model.file,
                                fit: BoxFit.cover,
                                width: 40,
                                height: 40,
                              )
                            : CachedNetworkImage(
                                imageUrl: value,
                                fit: BoxFit.cover,
                                width: 40,
                                height: 40,
                              ),
                      ),
                      SizedBox(width: 16),
                    ],
                  ),
                ),
                onTap: () {
                  _onAvatarClicked(context);
                },
              );
          }
        },
      ),
    );
  }

  void _onAvatarClicked(BuildContext context) async {
    var result = await showModalBottomSheet(
      context: context,
      builder: (context) {
        return _BottomSheetWidget();
      },
    );
    debugPrint('result = $result');
    if (result == null) {
      return;
    }
    UserAvatarUpdateModel model = Provider.of(context, listen: false);
    model.file = result;
    var viewStatue = await model.userAvatarUpdate();
    switch (viewStatue) {
      case ViewState.error:
        showToast(model.errorMessage);
        break;
      default:
        showToast('更新成功');
        break;
    }
  }
}

class _BottomSheetWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: <Widget>[
          ListTile(
            title: Text('拍照'),
            onTap: () {
              _onItemClicked(context, ImageSource.camera);
            },
          ),
          ListTile(
            title: Text('从相册选择'),
            onTap: () {
              _onItemClicked(context, ImageSource.gallery);
            },
          ),
        ],
      ),
    );
  }

  void _onItemClicked(BuildContext context, ImageSource source) async {
    var file = await ImagePicker.pickImage(
      source: source,
      maxWidth: 200,
      maxHeight: 200,
    );
    Navigator.of(context).pop(file);
  }
}

class _ItemQRCodeWidget extends StatelessWidget {
  final String title;

  const _ItemQRCodeWidget({
    Key key,
    @required this.title,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 45,
      child: Row(
        children: <Widget>[
          SizedBox(width: 17),
          Expanded(
            child: Text(
              title,
              style: TextStyle(fontSize: 16),
            ),
          ),
          Image.asset(
            'assets/images/user/ic_qr_code.png',
            width: 18,
          ),
          SizedBox(width: 8),
          Icon(
            Icons.keyboard_arrow_right,
            color: Colors.grey,
          ),
          SizedBox(width: 8),
        ],
      ),
    );
  }
}

class _ItemTextWidget extends StatelessWidget {
  final String title;
  final String value;
  final Function onTap;
  final bool showArrow;

  const _ItemTextWidget({
    Key key,
    @required this.title,
    @required this.value,
    this.onTap,
    this.showArrow = true,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Container(
        height: 45,
        child: Row(
          children: <Widget>[
            SizedBox(width: 17),
            Expanded(
              child: Text(
                title,
                style: TextStyle(fontSize: 16),
              ),
            ),
            Text(
              value ?? '--',
              style: TextStyle(color: Colors.grey),
            ),
            SizedBox(width: 8),
            if (showArrow)
              Icon(
                Icons.keyboard_arrow_right,
                color: Colors.grey,
              ),
            SizedBox(width: 8),
          ],
        ),
      ),
      onTap: onTap,
    );
  }
}
